﻿using System;
using System.Threading.Tasks;
using System.Web.Http;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Web.Models;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using LeadThing.AbpZeroTemplate.Authorization;
using LeadThing.AbpZeroTemplate.Authorization.Users;
using LeadThing.AbpZeroTemplate.MultiTenancy;
using LeadThing.AbpZeroTemplate.WebApi.Models;
using System.Web;
using LeadThing.AbpZeroTemplate.Files.Dtos;
using System.IO;
using LeadThing.AbpZeroTemplate.Files;
using Abp.Runtime.Session;
using LeadThing.AbpZeroTemplate.Authorization.Users.Dto;
using LeadThing.AbpZeroTemplateShortMessage;
using System.Xml;
using LeadThing.AbpZeroTemplate.CameraManages;
using LeadThing.AbpZeroTemplate.Areas.Dtos;
using LeadThing.AbpZeroTemplate.Areas;
using LeadThing.AbpZeroTemplate.CameraManages.Dtos;
using System.Text;

namespace LeadThing.AbpZeroTemplate.WebApi.Controllers
{
    public class DataSynchronizationController : AbpZeroTemplateApiControllerBase
    {

        private readonly ICameraManageAppService _cameraManageAppService;
        private readonly IAreaAppService _areaService;


        public DataSynchronizationController(IAreaAppService areaService,
            ICameraManageAppService cameraManageAppService)
        {
            _areaService = areaService;
            _cameraManageAppService = cameraManageAppService;
        }


        [HttpPost]
        public async Task<AjaxResult> DataSynchronization()
        {
            AjaxResult result = new AjaxResult();
            try
            {
                #region 同步操作
                Random rd = new Random();
                XmlDocument dom = new XmlDocument();
                dom.Load("D:\\组织树.xml");

                //获取组织树、部门节点
                XmlNodeList topM = dom.SelectNodes("//Department[@coding]");

                //清空摄像头表数据
                if (topM.Count > 0)
                {
                    var count = _cameraManageAppService.DeleteAllCameraManages();
                }

                for (int i = 0; i < topM.Count; i++)
                {
                    XmlNode node = topM[i];
                    string cameraId = string.Empty;//摄像头id
                    string XPoint = string.Empty;//经度
                    string YPoint = string.Empty;//维度

                    if (node.Attributes["coding"] == null)
                    {
                        continue;
                    }

                    cameraId = node.Attributes["coding"].Value;
                    GetAreaInput input = new GetAreaInput() { CameraID = cameraId };
                    var areaModel = await _areaService.GetAreaByCameraIdAsync(input);
                    if (areaModel == null && cameraId != "001001")
                    {
                        continue;
                    }
                    //加入001001这个特殊情况
                    if (cameraId == "001001")
                    {
                        XPoint = "118.83002";
                        YPoint = "35.5811";
                    }
                    else
                    {
                        XPoint = areaModel.XPoint;
                        YPoint = areaModel.YPoint;
                    }

                    //坐标是否合理
                    if (string.IsNullOrWhiteSpace(XPoint) || double.Parse(XPoint) == 0 || string.IsNullOrWhiteSpace(YPoint) || double.Parse(YPoint) == 0)
                    {
                        continue;
                    }

                    //获取Channel监控节点列表  
                    XmlNodeList twoM = node.SelectNodes("Channel");
                    for (int j = 0; j < twoM.Count; j++)
                    {
                        XmlNode twoNode = twoM[j];
                        string channelId = twoNode.Attributes["id"].Value;

                        XmlNode threeNode = dom.SelectSingleNode($"//Channel[@id='{channelId}'][@name]");

                        if (threeNode == null)
                        {
                            continue;
                        }
                        CameraManageEditDto addModel = new CameraManageEditDto();
                        addModel.CameraId = threeNode.Attributes["id"].Value;

                        if (threeNode.Attributes["name"] != null)
                            addModel.CameraName = threeNode.Attributes["name"].Value;
                        if (threeNode.Attributes["status"] != null)
                            addModel.Status = threeNode.Attributes["status"].Value;
                        if (threeNode.Attributes["channelType"] != null)
                            addModel.ChannelType = threeNode.Attributes["channelType"].Value;
                        if (threeNode.Attributes["channelSN"] != null)
                            addModel.ChannelSN = threeNode.Attributes["channelSN"].Value;
                        if (threeNode.Attributes["rights"] != null)
                            addModel.Rights = threeNode.Attributes["rights"].Value;
                        if (threeNode.Attributes["cameraType"] != null)
                            addModel.CameraType = threeNode.Attributes["cameraType"].Value;
                        if (threeNode.Attributes["ctrlId"] != null)
                            addModel.CtrlId = threeNode.Attributes["ctrlId"].Value;

                        StringBuilder xsb = new StringBuilder();
                        for (int h = 0; h < 2; h++)
                        {
                            xsb.Append(rd.Next(1, 10).ToString());
                        }

                        StringBuilder ysb = new StringBuilder();
                        for (int h = 0; h < 2; h++)
                        {
                            ysb.Append(rd.Next(1, 10).ToString());
                        }

                        if (YPoint.Length > 2)
                        {
                            addModel.Longitude = YPoint.Substring(0, YPoint.Length - 2) + xsb.ToString();
                        }

                        if (XPoint.Length > 2)
                        {
                            addModel.Latitude = XPoint.Substring(0, XPoint.Length - 2) + ysb.ToString();
                        }

                        //if (threeNode.Attributes["latitude"] != null)
                        //    addModel.Latitude = threeNode.Attributes["latitude"].Value;
                        //if (threeNode.Attributes["longitude"] != null)
                        //    addModel.Longitude = threeNode.Attributes["longitude"].Value;
                        if (threeNode.Attributes["viewDomain"] != null)
                            addModel.ViewDomain = threeNode.Attributes["viewDomain"].Value;
                        if (threeNode.Attributes["cameraFunctions"] != null)
                            addModel.CameraFunctions = threeNode.Attributes["cameraFunctions"].Value;
                        if (threeNode.Attributes["multicastIp"] != null)
                            addModel.MulticastIp = threeNode.Attributes["multicastIp"].Value;
                        if (threeNode.Attributes["multicastPort"] != null)
                            addModel.MulticastPort = threeNode.Attributes["multicastPort"].Value;
                        if (threeNode.Attributes["nvrChnlIp"] != null)
                            addModel.NvrChnlIp = threeNode.Attributes["nvrChnlIp"].Value;
                        if (threeNode.Attributes["channelRemoteType"] != null)
                            addModel.ChannelRemoteType = threeNode.Attributes["channelRemoteType"].Value;
                        if (threeNode.Attributes["subMulticastIp"] != null)
                            addModel.SubMulticastIp = threeNode.Attributes["subMulticastIp"].Value;
                        if (threeNode.Attributes["subMulticastPort"] != null)
                            addModel.SubMulticastPort = threeNode.Attributes["subMulticastPort"].Value;


                        if (cameraId == "001001")
                        {
                            addModel.TownID = 0;
                            addModel.AreaID = 0;
                            addModel.VillageID = 0;
                        }
                        else
                        {
                            addModel.TownID = areaModel.TownID;
                            addModel.AreaID = areaModel.AreaID;
                            addModel.VillageID = areaModel.VillageID;
                        }
                        //不存在就添加
                        var re = await _cameraManageAppService.CreateCameraManageAsync(addModel);
                    }
                }
                #endregion

                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
            }
            return result;
        }


    }
}
